package cn.dglydrpy.study.j2ee.neo4j;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 内嵌的neo4j
 * @author LY_飘涯
 *
 */
public class EmbeddedNeo4jTest {
    private  static final File databaseDirectory = new File("target/graph.db");
    
    public static void main(String[] args) {
        // 创建数据库服务对象
        GraphDatabaseService  graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory);
        System.out.println("database load!");
        // 获取事务  开启事务
        Transaction tx = graphDatabaseService.beginTx();
        Node n1 = graphDatabaseService.createNode();
        n1.setProperty("name","张三");
        n1.setProperty("character","A");
        n1.setProperty("money",1101);
        n1.addLabel(new Label() {
            @Override
            public String name() {
                return "Person";
            }
        });
        // 定义cql
        String  cql = "CREATE(p:Person {name:'李四',character:'B',money:21000})";
        graphDatabaseService.execute(cql);
        tx.success();
        tx.close();
//        graphDatabaseService.shutdown();

        System.out.println("========== 查询 ==========");
        
        // 创建数据库服务对象
        String cqlfind = "MATCH(p:Person) where p.money < $money return p";
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("money",25000);
        // 获取事务  开启事务  neo4j语句必须放在事务里执行,即使是查询 甚至单个语句 都必须开启事务
        Transaction  tx2 = graphDatabaseService.beginTx();
        
        /**
         * 返回的对象可能是多个  eg: match(xxx) return o1,o2
         */
        Result result = graphDatabaseService.execute(cqlfind,parameters);
        while (result.hasNext()){
            Map<String,Object> row = result.next();
            System.out.println(row);
            for(String key : result.columns()){
                Node nd = (Node) row.get(key);
                System.out.printf("%s=%s:%s%n",key,nd.getProperty("name"),nd.getProperty("money"));
            }
        }
        tx2.success();
        tx2.close();
        graphDatabaseService.shutdown();
        System.out.println("database shutdown");
    }
}
